<?php

namespace App\Traits;

use App\Common\Constant;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Matrix\Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

/**
 * excel 导出文件 Trait
 *
 * @author WangBin
 * @date 2021/9/01
 */
trait ExcelWriter
{
    /**
     * 写入 excel 文件内容
     *
     * @param string $filename 文件名称（不含路径）
     * @param array $data
     * @return bool $result
     * @author WangBin
     * @date 2021/8/20
     */
    public function writer(string $filename, array $header, array $data = [])
    {
        ini_set('max_execution_time', 0);
        $result = false;
        try {
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            if(empty($header)) {
                throw new Exception('excel 标题栏为空');
            }
            // 生成标题栏数据
            foreach ($header as $column => $value)
            {
                $sheet->setCellValue($column . '1', $value);
            }
            // 生成数据栏数据
            foreach ($data as $row => $item)
            {
                $row = $row + 2;
                foreach ($item as $column => $value)
                {
                    $key = $column + 1;
                    $index = Coordinate::stringFromColumnIndex($key);
                    $sheet->setCellValue($index . $row, $value);
                }
            }
            // 写入 excel 文件到服务器
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
            // 目录不存在则创建
            if(Storage::missing(Constant::EXCEL_EXPORT_PATH)) {
                Storage::makeDirectory(Constant::EXCEL_EXPORT_PATH);
            }
            $writer->save(Storage::path(Constant::EXCEL_EXPORT_PATH) . $filename);
            $result = true;
        } catch (\Exception $exception) {
            Log::error("[excel生成文件] 生成 excel 失败：{$exception->getMessage()}");
        }
        return $result;
    }
}
